package com.ocm.tourism.core.service;

import com.ocm.tourism.core.dao.ParticipantDao;
import com.ocm.tourism.core.domain.Participant;
import com.ocm.tourism.core.model.SearchCriteria;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("participantService")
public class ParticipantServiceImpl implements ParticipantService {

   @Autowired
   ParticipantDao participantDao;

   public long countAllParticipants() {
      return participantDao.count();
   }

   public void deleteParticipant(Participant participant) {
      participantDao.remove(participant.getId());
   }

   public Participant findParticipant(Long id) {
      return participantDao.find(id);
   }

   public List<Participant> findParticipants(int firstResult, int maxResults) {
      return participantDao.findAll(firstResult, maxResults);
   }

   @Transactional(readOnly=false, propagation=Propagation.REQUIRED)
   public void saveParticipant(Participant participant) {
      if (participant.getId() == null || participant.getId() == 0)
         participantDao.save(participant);
      else
         participantDao.update(participant);
   }

   @Override
   public boolean hasParticipant(String username) {
      boolean has = participantDao.hasParticipant(username);
      return has;
   }

   @Override
   @Transactional
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      Participant participant = this.participantDao.findByUserName(username);
      if (participant != null){
         return participant.convertToUserInfo();
      }
      return null;
   }

   @Override
   public List<Participant> findParticipants(SearchCriteria participantCriteria, int firstResult, int maxResults) {
      List<Participant> participants = this.participantDao.findParticipants(participantCriteria, firstResult, maxResults);
      return participants;
   }

}
